/*
 * SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: Unlicense OR CC0-1.0
 */

#include <stdlib.h>
#include <string.h>
#include "esp_err.h"
#include "esp_log.h"
#include "esp_wifi.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "protocol_examples_common.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"

#include "bsp/esp32_s3_lcd_ev_board.h"
#include "lvgl.h"
#include "ui/ui.h"
#include "app_sntp.h"
#include "app_mqtt.h"
#include "bsp_board_extra.h"
#include "app_ui_control.h"
#include "app_play_music.h"
#include "app_sr.h"

static const char *TAG = "main";

// *INDENT-OFF*
void app_lvgl_display(void)
{
    bsp_display_lock(0);

    ui_init();

    bsp_display_unlock();
}

void app_main(void)
{
    ESP_ERROR_CHECK(nvs_flash_init());
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
     * Read "Establishing Wi-Fi or Ethernet Connection" section in
     * examples/protocols/README.md for more information about this function.
     */
    ESP_ERROR_CHECK(example_connect());

    /* Initialize SNTP */
    app_sntp_init();

    /* Initialize audio */
    bsp_extra_codec_init();
    ESP_ERROR_CHECK(app_sr_start());

    bsp_spiffs_mount();

    /* Initialize audio player */
    bsp_extra_player_init(NULL);
    app_music_player_init();

    /* Initialize display and LVGL */
    bsp_display_start();

    /* Add and show objects on display */
    app_lvgl_display();

    mqtt_app_start();

    /* Set LVGL clock */
    ui_timer_init();

    ESP_LOGI(TAG, "Free memory after start: %d bytes", heap_caps_get_total_size(MALLOC_CAP_INTERNAL));

    while (1) {
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}
